import 'package:flutter/material.dart';
import 'dart:io';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

class DemoScreen extends StatefulWidget {

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new DemoScreenState();
  }
}


class DemoScreenState extends State<DemoScreen> {
  late InAppWebViewController webView;
  String url = "";
  double progress = 0;

  @override
  void initState() {
    super.initState();
    _init();
  }

  _init() async {
    if (Platform.isAndroid) {
      await AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true);
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(

        title: Text('h5交互',style:TextStyle(fontSize: 17)),
        centerTitle: true,

      ),
      body: Column(children: <Widget>[
        Container(
          padding: EdgeInsets.all(20.0),
          child: Text(
              "CURRENT URL\n${(url.length > 50) ? url.substring(0, 50) + "..." : url}"),
        ),
        Container(
            padding: EdgeInsets.all(10.0),
            child: progress < 1.0 ? LinearProgressIndicator(value: progress) : null
        ),
        Expanded(
          child: InAppWebView(
            initialFile: "images/demo.html",
            onWebViewCreated: (InAppWebViewController controller) {
              webView = controller;

              _lis();
            },
            onLoadStart: (InAppWebViewController controller, Uri? url) {
              print("started $url");
              setState(() {
                this.url = (url).toString();
              });
            },
            onLoadStop: (InAppWebViewController controller, Uri? url) async {
              print("stopped $url");
            },
            onProgressChanged:
                (InAppWebViewController controller, int progress) {
              setState(() {
                this.progress = progress / 100;
              });
            },
            shouldOverrideUrlLoading: (InAppWebViewController controller, NavigationAction navigationAction) async {
              Uri? url = navigationAction.request.url;
              print("override $url");
              controller.loadUrl(urlRequest: URLRequest(url: url));
              return NavigationActionPolicy.ALLOW;
            },
            onLoadResource: (InAppWebViewController controller, LoadedResource resource) {
              print("Started at: " +
                  resource.startTime.toString() +
                  "ms ---> duration: " +
                  resource.duration.toString() +
                  "ms " +
                  resource.url.toString());
            },
            onConsoleMessage: (InAppWebViewController controller, ConsoleMessage consoleMessage) {
              print("""
              console output:
                message: ${consoleMessage.message}
                messageLevel: ${consoleMessage.messageLevel}
              """);
            },
          ),
        ),
        ButtonBar(
          alignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              child: Text('修改h5样式'),
              onPressed: () async {
                if (webView != null) {
                  webView.callAsyncJavaScript(functionBody: '''
                    document.body.style.backgroundColor = 'green';
                  ''',
                     );
                  var result3 =  await webView.evaluateJavascript(source: "window.appSendJs('hello abcd')");
                  print(result3);
                }
              },
            ),
            RaisedButton(
              child: Text('发送消息给h5'),
              onPressed: () {
                if (webView != null) {
                  webView.callAsyncJavaScript(functionBody: "window.appSendJs('hello')");
                  // webView.addJavaScriptHandler(handlerName: "window.appSendJs('hello')"
                  //     ,
                  //     callback:  (List<dynamic> arguments){
                  //       print(arguments);
                  //     });
                }
              },
            ),
            RaisedButton(
              child: Icon(Icons.refresh),
              onPressed: () {
                if (webView != null) {
                  webView.reload();
                }
              },
            ),
          ],
        ),
      ]),

    );
  }

  _lis() async {
    webView.addJavaScriptHandler(handlerName: 'ping',callback:  (args) {
      print("收到来自web的消息 ping");
      print(args);
    });

    webView.addJavaScriptHandler(handlerName: 'handlerFooWithArgs',callback:  (args) {
      print(args);
      return [args[0] + 5, !args[1], args[2][0], args[3]['foo']];
    });
  }
}
